<template>
	<div class="tbk">
    <Affix >
      <div class="tbk-top">
        <Input v-model="keyWord"   style="width: 200px;margin:0 auto;">
          <span slot="append" @click="getTbkItem">搜索</span>
        </Input>
      </div>
    </Affix>
    <div id="macy-container" ref="macy" style="     overflow: hidden;">
      <div  class="tbk-item-list ivu-card-bordered" v-for="item in tbkItemList">
        <div class="tbk-item-list-img" >
          <a :href="item.item_url" target="_blank">
            <img :src="item.pict_url+'_240x240q90.jpg'" alt="" style="width:100%;">
          </a>
        </div>        
        <div class="item-title">
          <tbk-item :item-info="item" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Macy from 'macy'
import TbkItem from './TheTbkItem.vue'
export default {
  name: 'Tbk',

  mixins: [],

  components: {TbkItem},

  props: {},

  data() {
    return {
      tbkItemList:[],//淘宝客商品
      keyWord:"",//关键字
      page:1,//页数
      isupdate:true,//是否下载中
      macyInstance:null,//布局工具
    };
  },

  computed: {},

  watch: {},

  created() {
    
  },

  mounted() {
    var macyInstance = Macy({
      container: '#macy-container',
      trueOrder: false,
      waitForImages: false,
      margin: 12,
      columns: 4,
      breakAt: {
        768: {
          columns: 2,
          margin: 6,
        }
      }
    });
    this.macyInstance=macyInstance;
    window.onscroll =  ()=> {
      let macy=this.$refs.macy;
      let Bottom=macy.offsetTop+macy.clientHeight-50;
      let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
      let scrollOff=scrollTop+window.innerHeight;
      if(scrollOff>Bottom&& !this.isupdate){
        this.addTbkItem();
      }
    };
  },

  updated(){
    this.macyonLoad();
  },
  destroyed() {},

  methods: {
    getTbkItem(){
      if(this.keyWord==''){
        return;
      }
      this.isupdate=true;
      this.page=1;
      this.$http.get('/tbk?q='+this.keyWord+'&page='+this.page)
      .then((response)=>{
        this.tbkItemList = response.data;
        //this.macyonLoad();
      });
    },
    addTbkItem(){
      if(this.isupdate||this.keyWord==''){
        return;
      }
      this.isupdate=true;
      this.$http.get('/tbk?q='+this.keyWord+'&page='+this.page)
      .then((response)=>{        
        this.tbkItemList = this.tbkItemList.concat(response.data); 
        //this.macyonLoad();
      });
    },
    macyonLoad(){
      this.isupdate=false;
      this.page++;
      this.macyInstance.runOnImageLoad( () =>{
        this.macyInstance.recalculate(true, true);
      });
    },
  }
}
</script>
<style >
.tbk-item-list{
  border: 1px solid #dddee1;
}
.tbk-item-list-img{
  padding: 5px;
}
.tbk-top{
  background: #fff;
  padding-top: 1rem;
  padding-bottom: 1rem;
}
.item-title{
  position:absolute;
  bottom: 1rem;
  right:1rem;
  text-align: center;
}
</style>